#include "at24c02.h"

static void I2C_Start()
{
	SDA = 1;
	SCL = 1;
	SDA = 0;
	SCL = 0;
}

static void I2C_Stop()
{
	SDA = 0;
	SCL = 1;
	SDA = 1;
}


static void I2C_SendByte(u8_t byte)
{
	u8_t i = 0;
	for(i = 0; i < 8; i++)
	{
		SDA = byte & (0x80 >> i);
		SCL = 1;
		SCL = 0;
	}
}

static u8_t I2C_ReceiveByte()
{
	u8_t ret = 0;
	u8_t i = 0;
	SDA = 1;
	
	for(i = 0; i < 8; i++)
	{
		SCL = 1;
		if(SDA)
		{
			ret |=  (0x80 >> i);
		}
		
		SCL = 0;
	}
	
	return ret;
}



static void I2C_SendAck(u8_t ack)
{
	SDA = ack;
	SCL = 1;
	SCL = 0;
}


static u8_t I2C_ReceiveAck(u8_t ack)
{
	u8_t ret = 0;
	SDA = 1;
	SCL = 1;
	ret = SDA;
	SCL = 0;
	return ret;
}


void AT24C02_WriteByte(u8_t address,u8_t Data)
{
	I2C_Start();
	I2C_SendByte(AT24C02_ADDRESS);
	I2C_ReceiveAck();
	I2C_SendByte(address);
	I2C_ReceiveAck();
	I2C_SendByte(Data);
	I2C_ReceiveAck();
	I2C_Stop();
	Delay(5);
}

u8_t AT24C02_ReadByte(u8_t address)
{
	u8_t ret;
	I2C_Start();
	I2C_SendByte(AT24C02_ADDRESS);
	I2C_ReceiveAck();
	I2C_SendByte(address);
	I2C_ReceiveAck();
	I2C_Start();
	I2C_SendByte(AT24C02_ADDRESS|0x01);
	I2C_ReceiveAck();
	ret = I2C_ReceiveByte();
	I2C_SendAck(1);
	I2C_Stop();
	return ret;
}
